#!/bin/bash

sleep 1

PROCESS_NAME="1_xPaciae40.x"
LOGFILE="memory_peak.log"

echo "Timestamp, PID, RSS (MB), VIRT (MB), Peak RSS (MB)" > "$LOGFILE"

PEAK_RSS_KB=0

while true; do
    PID=$(pgrep -x "$PROCESS_NAME")

    if [ -z "$PID" ]; then
        echo "Process $PROCESS_NAME not found. Exiting."
        break
    fi

    RSS_KB=$(awk '/VmRSS/{print $2}' /proc/$PID/status)
    VIRT_KB=$(awk '/VmSize/{print $2}' /proc/$PID/status)

    RSS_MB=$(awk "BEGIN {printf \"%.2f\", $RSS_KB / 1024}")
    VIRT_MB=$(awk "BEGIN {printf \"%.2f\", $VIRT_KB / 1024}")

    if [ "$RSS_KB" -gt "$PEAK_RSS_KB" ]; then
        PEAK_RSS_KB=$RSS_KB
    fi

    PEAK_RSS_MB=$(awk "BEGIN {printf \"%.2f\", $PEAK_RSS_KB / 1024}")

    echo "$(date '+%Y-%m-%d %H:%M:%S'), $PID, $RSS_MB MB, $VIRT_MB MB, $PEAK_RSS_MB MB" >> "$LOGFILE"

    sleep 10
done

PEAK_RSS_GB=$(awk "BEGIN {printf \"%.2f\", $PEAK_RSS_KB / 1048576}")
echo "Process ended. Peak Resident Memory: $PEAK_RSS_MB MB ($PEAK_RSS_GB GB)" >> "$LOGFILE"